#include "Nests.h"
#include "math.h"

float Nests::fixedAngle = M_PI / 12;

Nests* Nests::CreateNestByFileName(const char* filename) {
	Nests *sprite = new Nests();
	if (sprite && sprite->initWithFile(filename)) {
		sprite->delta = sprite->getContentSize().width / 2;
		return sprite;
	}
	CC_SAFE_DELETE(sprite);
	return NULL;
}

Nests::Nests() {
	screenWidth = CCDirector::sharedDirector()->getVisibleSize().width;
	screenHeight =
			CCDirector::sharedDirector()->getVisibleSize().height;
	time = rand() % 4 + 4;
	direction = rand() % 2;
	isChangedDirection = false;
	moveAngle = 0;
	if (rand() % 5 == 0) {
		moveAngle = fixedAngle;
	}
	behindNests = NULL;
}

int Nests::getId() {
	return id;
}

void Nests::movedown(float delta){
	startpoint = ccp(startpoint.x, startpoint.y-delta);
	endtpoint = ccp(endtpoint.x, endtpoint.y-delta);
}

void Nests::setposition(float y) {

	int range = screenWidth - 3 * delta;

	if (behindNests && behindNests->moveAngle != 0) moveAngle = 0;

    if (moveAngle != 0){
    	if (!direction) {
    			startpoint = ccp(delta,y-screenWidth*tan(fixedAngle)/(2));
    			endtpoint = ccp(screenWidth-delta,y+screenWidth*tan(fixedAngle)/(2));
    		} else {
    			endtpoint = ccp(screenWidth-delta,y-screenWidth*tan(fixedAngle)/(2));
    			startpoint = ccp(delta,y+screenWidth*tan(fixedAngle)/(2));
    		}
    range = screenWidth/2 - 3 * delta;
    }else{
    	startpoint = ccp(delta,y);
    	endtpoint = ccp(screenWidth-delta,y);
    }

    float x = rand()%range + startpoint.x + 0.2*delta;
    if (moveAngle){
    	if (direction){
    		y-= (x-screenWidth/2)*tan(moveAngle);
    	}else{
    		y+= (x-screenWidth/2)*tan(moveAngle);
    	}
    }


	this->setPosition(ccp(x,y));
}

void Nests::setBehindNest(Nests* nests) {
	behindNests = nests;
}

void Nests::Start() {
	this->stopAllActions();
	float distance;
	float currentX = this->getPositionX();
	float delta = this->getContentSize().width / 2;
	if (this->getPositionX() <= startpoint.x
			|| this->getPositionX() >= endtpoint.x) {
		direction = 1 - direction;
		isChangedDirection = true;
	} else {

	}
	CCPoint dest;
	if (direction){
		dest = startpoint;
	}else{
		dest = endtpoint;
	}

	distance = Utils::distance(this->getPosition(), dest);

	float movetime;

	movetime = kVelocity*time*distance / Utils::distance(startpoint, endtpoint);
	CCLog("MOVE TIME = %f", movetime);
	CCMoveTo *move = CCMoveTo::create(movetime, dest);

	CCCallFuncN *funcdone = CCCallFuncN::create(this,
			callfuncN_selector(Nests::Start));

	this->runAction(CCSequence::create(move, funcdone, NULL));

}
void Nests::Stop() {
	this->stopAllActions();

}

